import axios from 'axios';
import { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { observer } from 'mobx-react-lite'
import { Table, Space, Card, Breadcrumb, Form, Button, Radio, DatePicker, Select,Modal, Input,message } from 'antd'
import { EditOutlined, DeleteOutlined, SearchOutlined,PlusOutlined,EllipsisOutlined  } from '@ant-design/icons'
import { useForm } from 'antd/lib/form/Form';
import CourseStudentAssignment from '../coursestudent';
const Student = () => {
  const [form] = useForm();
  const [data, setData] = useState([]);
  const [newItem, setNewItem] = useState('');
  const [length, setlength] = useState('');
  const [editingItem, setEditingItem] = useState(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isaddModalVisible, setIsaddModalVisible] = useState(false);
  const [iscourseModalVisible, setIscourseModalVisible] = useState(false);
  const [isallocation, setIsallocation] = useState(false);
  const [editedData, setEditedData] = useState(null);
  const [addData, setaddData] = useState(null);
  const [takeData, settakeData] = useState(null);
  const [stuid, setstuid] = useState(null);
  const [params,setParams] = useState({
    page:1,
    perpage:5
  })
  const [searchInput, setSearchInput] = useState('');
  useEffect(() => {
    axios.get('http://localhost:8000/getstudentlist',{ params })
      .then(response => {
        console.log(response.data.list);
        setData(response.data.list);
        setlength(response.data.length);
       // console.log(params); // Updated data
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, [params]);
  

  // 翻页实现
  const pageChange = (page) => {
    setParams({
      ...params,
      page
    })
  }
  const pageSizeChange = (value) => {
    setParams({
      ...params,
      perpage: value,
      page: 1 // Reset to the first page when changing page size
    });
  };
  
  // 删除
  
  const del = async (data) => {
    //console.log(data.id);
    try {
      // 假设你的后端 API 提供了删除学生的端点
      await axios.delete(`http://localhost:8000/deleteStudent/${data.id}`);
  
      // 更新 params 以触发重新获取数据
      axios.get('http://localhost:8000/getstudentlist',{ params })
      .then(response => {
        console.log(response.data.list);
        setData(response.data.list);
        setlength(response.data.length);
       // console.log(params); // Updated data
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
      message.success('删除成功');
    } catch (error) {
      //console.error('删除数据时发生错误:', error);
    }
  };
  
  const change = (data) => {
    //console.log(data);
    setEditedData(data);
    setIsModalVisible(true);
  }

  useEffect(() => {
    //console.log(editedData);
    if (editedData !== null) {
      form.setFieldsValue({
        studentid: editedData?.studentid,
        password: editedData?.password,
        username: editedData?.username,
        grade: editedData?.grade,
        class: editedData?.class,
        major: editedData?.major,
        // 其他字段...
      });
      setIsModalVisible(true);
    }
  }, [editedData, form]);

  const handleOk = () => {
    const id = editedData?.id;
    const values = form.getFieldsValue(); // 获取表单修改后的值
    console.log('修改后的表单值:', values, id);
    axios.post('http://localhost:8000/changestudent', { id, values,params })
      .then(response => {
        // 处理来自后端的响应
        console.log('成功发送到后端并收到响应:', response.data);
        setIsModalVisible(false);
        axios.get('http://localhost:8000/getstudentlist',{ params })
        .then(response => {
          //console.log(response.data.list);
          setData(response.data.list);
          setlength(response.data.length);
         // console.log(params); // Updated data
        })
      })
      .catch(error => {
        // 处理来自后端的任何错误
        console.error('与后端通信时发生错误:', error);
      });
  };
  

  const handleCancel = () => {
    setIsModalVisible(false);
    //setEditedData([])
  };


  const onSearch = () => {
    // 发起搜索请求
    axios.get('http://localhost:8000/searchstudent', { params: { keyword: searchInput } })
      .then(response => {
        setData(response.data.results);
        setlength(response.data.length);
      })
      .catch(error => {
        console.error('Error searching data:', error);
      });
  };


  const add = (data) => {
    //console.log(data);
    setaddData(data);
    setIsaddModalVisible(true);
  }

  useEffect(() => {
    //console.log(addData);
    if (addData !== null) {
      form.setFieldsValue({
        studentid: addData?.studentid,
        username: addData?.username,
        password: addData?.password,
        grade: addData?.grade,
        class: addData?.class,
        major: addData?.major,
        // 其他字段...
      });
      setIsaddModalVisible(true);
    }
  }, [addData, form]);

  const addOk = () => {
    const values = form.getFieldsValue(); // 获取表单修改后的值
    const allValuesEmpty = Object.values(values).every(value => !value); // 检查是否所有值都为空
    
    if (!allValuesEmpty) {
      console.log('修改后的表单值:', values);
      axios.post('http://localhost:8000/addstudent', { values })
        .then(response => {
          // 处理来自后端的响应
          console.log('成功发送到后端并收到响应:', response.data);
          setIsaddModalVisible(false);
          axios.get('http://localhost:8000/getstudentlist',{ params })
            .then(response => {
              //console.log(response.data.list);
              setData(response.data.list);
              setlength(response.data.length);
             // console.log(params); // Updated data
             message.success('添加成功');
            })
        })
        .catch(error => {
          // 处理来自后端的任何错误
          console.error('与后端通信时发生错误:', error);
        });
    } else {
      message.error('表单值全部为空，不执行请求');
    }
  };
  

  const addCancel = () => {
    setIsaddModalVisible(false);
    //setEditedData([])
  };

  const allocation = () => {
    setIsallocation(true);
    //setEditedData([])
  };
  const allocationCancel = () => {
    setIsallocation(false);
    //setEditedData([])
  };

  const takecourse= (data) => {
    setIscourseModalVisible(true);
    console.log(data.studentid);
    const studentid = data.studentid;
    axios.post('http://localhost:8000/gettakecourselist', { studentid: studentid })
    .then(response => {
      // 处理从后端返回的数据
      console.log(response.data);
      settakeData(response.data);
      setstuid(data.studentid);
    })
    .catch(error => {
      console.error('Error:', error);
    });
    
    //setEditedData([])
  };

  const takeCancel = () => {
    setIscourseModalVisible(false);
    //setEditedData([])
  };

  const deltake = async (data) => {
    console.log(data.courseid);
    console.log(stuid);

    try {
      // 假设你的后端 API 提供了删除的端点
      const requestData = {
        courseid: data.courseid,
        studentid: stuid
      };
      console.log(requestData);
      await axios.post('http://localhost:8000/deletecoursetakes', requestData);
  
      // 更新 params 以触发重新获取数据
      axios.post('http://localhost:8000/gettakecourselist', { studentid: stuid })
    .then(response => {
      // 处理从后端返回的数据
      console.log(response.data);
      settakeData(response.data);
    })
    .catch(error => {
      console.error('Error:', error);
    });
      message.success('删除成功');
    } catch (error) {
      //console.error('删除数据时发生错误:', error);
    }
   
  };


  const columns = [
    {
      title: '学号',
      dataIndex: 'studentid',
      width: 120
    },
    {
      title: '姓名',
      dataIndex: 'username',
    },
    {
      title: '年级',
      dataIndex: 'grade'
    },
    {
      title: '班级',
      dataIndex: 'class'
    },
    {
      title: '专业',
      dataIndex: 'major'
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => change(data)} 
            />
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => del(data)}
            />
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<EllipsisOutlined />}
              style={{ color: 'white', backgroundColor: 'black' }}
              onClick={() => takecourse(data)}
            />
          </Space>
        )
      },
      fixed: 'right'
    }
  ]

  const columns2 = [
    {
      title: '课程编号',
      dataIndex: 'courseid',
      width: 120
    },
    {
      title: '课程',
      dataIndex: 'coursename',
    },
    {
      title: '属性',
      dataIndex: 'attribute'
    },
    {
      title: '最大学生数量',
      dataIndex: 'studentnum'
    },
    {
      title: '当前学生数量',
      dataIndex: 'num'
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => deltake(data)}
            />
          </Space>
        )
      },
      fixed: 'right'
    }
  ]


  return (
    <div>
      <h1>Student Page</h1>
      <Card>
        <Input 
          value={searchInput} 
          onChange={(e) => setSearchInput(e.target.value)} 
          style={{ width: 200 }}
          placeholder="输入关键词"
        />
        <Button 
          type="primary" 
          icon={<SearchOutlined />} 
          onClick={onSearch}
          style={{ marginLeft: 10 }}
        >
          搜索
        </Button>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={add}
          style={{ marginLeft: 10 }}
        >
          添加用户
        </Button>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={allocation}
          style={{ marginLeft: 10 }}
        >
          课程调整
        </Button>
      </Card>
      <Card title={`根据筛选条件共查询到 ${length} 条结果：`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          pagination={
            {
              pageSize: params.perpage,
              onChange: pageChange,
              current: params.page,
              total: length
            }
          }
        />
      </Card>
      
      <Modal
        title="修改信息"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        >
          {/* 这里添加表单字段，用于修改数据 */}
          <Form.Item label="学号" name="studentid" initialValue={editedData?.studentid}>
            <Input />
          </Form.Item>
          <Form.Item label="密码" name="password" initialValue={editedData?.password}>
            <Input />
          </Form.Item>
          <Form.Item label="学生名称" name="username" initialValue={editedData?.username}>
            <Input />
          </Form.Item>
          <Form.Item label="年级" name="grade" initialValue={editedData?.grade}>
            <Input />
          </Form.Item>
          <Form.Item label="班级" name="class" initialValue={editedData?.class}>
            <Input />
          </Form.Item>
          <Form.Item label="专业" name="major" initialValue={editedData?.major}>
            <Input />
          </Form.Item>
          {/* 添加其他表单字段... */}
        </Form>
      </Modal>

      <Modal
        title="添加用户"
        visible={isaddModalVisible}
        onOk={addOk}
        onCancel={addCancel}
      >
        <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        >
          {/* 这里添加表单字段，用于修改数据 */}
          <Form.Item label="学号" name="studentid" initialValue={addData?.studentid}>
            <Input />
          </Form.Item>
          <Form.Item label="密码" name="password" initialValue={addData?.password}>
            <Input />
          </Form.Item>
          <Form.Item label="学生名称" name="username" initialValue={addData?.username}>
            <Input />
          </Form.Item>
          <Form.Item label="年级" name="grade" initialValue={addData?.grade}>
            <Input />
          </Form.Item>
          <Form.Item label="班级" name="class" initialValue={addData?.class}>
            <Input />
          </Form.Item>
          <Form.Item label="专业" name="major" initialValue={addData?.major}>
            <Input />
          </Form.Item>
          {/* 添加其他表单字段... */}
        </Form>
      </Modal>

      <Modal
  title="已选课程"
  visible={iscourseModalVisible}
  onOk={null}
  onCancel={takeCancel}
  footer={null} 
>
  <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
    <Table dataSource={takeData} columns={columns2} />
  </Form>
</Modal>

      <Modal
  title="课程分配"
  visible={isallocation}
  onOk={null}
  onCancel={allocationCancel}
  footer={null} 
>
<CourseStudentAssignment/>
</Modal>
    </div>
  );
};

export default  Student;